import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'Login',
      component: () => import('../views/Login.vue'),
      meta: { requiresGuest: true } // 需要未登录状态才能访问
    },
    {
      path: '/register',
      name: 'Register',
      component: () => import('../views/Register.vue'),
      meta: { requiresGuest: true } // 需要未登录状态才能访问
    },
    {
      path: '/my-appointments',
      name: 'my-appointments',
      component: () => import('../views/MyAppointments.vue'),
      meta: { requiresAuth: true } // 需要登录才能访问
    },
    {
      path: '/home',
      name: 'home',
      component: HomeView,
      meta: { requiresAuth: true } // 需要登录才能访问
    },
    {
      path: '/about',
      name: 'about',
      component: () => import('../views/AboutView.vue'),
      meta: { requiresAuth: true } // 需要登录才能访问
    },
    {
      path: '/knowledge',
      name: 'knowledge',
      component: () => import('../views/KnowledgeBase.vue'),
    },
    {
      path: '/auth/dingtalk/callback',
      name: 'DingTalkCallback',
      component: () => import('../views/DingTalkCallback.vue'),
      meta: { public: true } // 公开页面，不需要守卫
    },
    {
      path: '/sms-test',
      name: 'SmsTest',
      component: () => import('../views/SmsTest.vue'),
      meta: { public: true } // 公开页面，不需要守卫
    },
    {
      path: '/appointment',
      name: 'appointment',
      component: () => import('../views/Appointment.vue'),
      meta: { requiresAuth: true } // 需要登录才能访问
    },
    {
      path: '/appointment/:doctorId',
      name: 'doctor-appointment',
      component: () => import('../views/DoctorAppointment.vue'),
    },
    {
      path: '/route-observer-demo',
      name: 'route-observer-demo',
      component: () => import('../views/RouteObserverDemo.vue'),
      meta: { requiresAuth: true } // 需要登录才能访问
    },
    {
      path: '/medical-record-audit',
      name: 'medical-record-audit',
      component: () => import('../views/MedicalRecordAudit.vue'),
      meta: { requiresAuth: true } // 需要登录才能访问
    },
    {
      path: '/image-recognition',
      name: 'image-recognition',
      component: () => import('../views/ImageRecognition.vue'),

      meta: { requiresAuth: true } // 需要登录才能访问
    },
      {
         path: '/doctors-iterator',
      name: 'doctors-iterator',
      component: () => import('../views/DoctorListWithIterator.vue'),
      }
  ],
})

// 检查用户是否已登录
function isAuthenticated() {
  const token = localStorage.getItem('token') || sessionStorage.getItem('token')
  return !!token
}

// 检查URL中是否有token参数(第三方登录回调)
function hasTokenInUrl(route) {
  return !!(route.query && route.query.token)
}

// 全局前置守卫
router.beforeEach((to, from, next) => {
  const isLoggedIn = isAuthenticated()
  const hasUrlToken = hasTokenInUrl(to)

  console.log('路由守卫:', {
    from: from.path,
    to: to.path,
    isLoggedIn,
    hasUrlToken,
    requiresAuth: to.meta.requiresAuth,
    requiresGuest: to.meta.requiresGuest
  })

  // 如果是公开页面，直接通过
  if (to.meta.public) {
    next()
    return
  }

  // 需要登录的页面
  if (to.meta.requiresAuth) {
    // 如果已登录或URL中有token(第三方登录回调)，允许访问
    if (isLoggedIn || hasUrlToken) {
      next() // 已登录或有token，允许访问
    } else {
      console.log('未登录，重定向到登录页面')
      // 清除历史记录中的认证页面，防止返回
      next({ path: '/', replace: true })
    }
    return
  }

  // 需要未登录状态的页面（登录页、注册页）
  if (to.meta.requiresGuest) {
    if (!isLoggedIn) {
      next() // 未登录，允许访问
    } else {
      console.log('已登录，重定向到首页')
      // 如果用户已登录但试图访问登录页，重定向到首页
      // 使用replace避免在历史记录中留下登录页面
      next({ path: '/home', replace: true })
    }
    return
  }

  // 默认情况下允许访问
  next()
})

// 全局后置钩子 - 处理路由完成后的逻辑
router.afterEach((to, from) => {
  const isLoggedIn = isAuthenticated()

  // 如果用户已登录并且刚刚访问了首页，清理浏览器历史记录中的登录相关页面
  if (isLoggedIn && to.path === '/home' && (from.path === '/' || from.path === '/register')) {
    // 使用 history.replaceState 来避免用户通过浏览器后退按钮返回到登录页
    window.history.replaceState(null, '', to.fullPath)
  }

  // 如果用户已退出登录并且访问登录页，清理历史记录中的认证页面
  if (!isLoggedIn && to.path === '/' && from.meta?.requiresAuth) {
    window.history.replaceState(null, '', to.fullPath)
  }
})

export default router


